<template>
  <!--  上传视频对话框  -->
  <div class="upload">
    <el-dialog title="上传视频" :visible.sync="isUpload" width="30%" :before-close="cancel">
      <el-form ref="formValidate" :model="uploadForm" :rules="ruleValidate" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input
            v-model.trim="uploadForm.title"
            placeholder="请输入">
          </el-input>
        </el-form-item>
        <el-form-item label="频道" prop="videoCategory">
          <el-select
            v-model="uploadForm.videoCategory.id"
            @change="$forceUpdate();"
            placeholder="请选择">
            <el-option
              v-for="item in channelOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标签" prop="label">
          <el-select
            v-model="uploadForm.label"
            @change="$forceUpdate();"
            multiple placeholder="请选择">
            <el-option
              v-for="item in tagOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="列表显示样式" prop="style">
          <el-radio v-model="uploadForm.style" label="image_text">图文显示</el-radio>
          <el-radio v-model="uploadForm.style" label="image">大图显示</el-radio>
        </el-form-item>
        <el-form-item label="简介" prop="content">
          <el-input
            type="textarea"
            :autosize="{ minRows: 3}"
            placeholder="请输入"
            v-model="uploadForm.content"
            style="width:200px">
          </el-input>
        </el-form-item>
        <el-form-item label="添加视频" prop="path">
          <upload
            :type="'video'"
            @handleRemove="handleVideoRemove"
            :file-list="uploadForm.path ? [`${uploadForm.path}`] : []"
            @handleSuccess="handleVideoSuccess"
            :max-size="5120"
            :limit="1"
            v-if="isFinished"
          >
          </upload>
          <div class="text">建议尺寸：750*300</div>
        </el-form-item>
        <el-form-item label="视频封面" prop="cover">
          <upload
            @handleRemove="handleImgRemove"
            :file-list="uploadForm.cover ? [`${uploadForm.cover}`] : []"
            @handleSuccess="handleImgSuccess"
            :max-size="5120"
            :limit="1"
            v-if="isFinished"
          >
          </upload>
          <div class="text">建议尺寸：750*300</div>
        </el-form-item>
        <el-form-item label="商品" prop="shop">
          <el-button type="success" @click="openShopWindow">商品橱窗</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>
    <shop-window
      @close="closeShopWindow"
      :id="id"
      :isShopWindow="isShopWindow">
    </shop-window>
  </div>
</template>

<script>
import ShopWindow from '@/framework/components/dialog/short-video/draft/shopWindow'
import Upload from '@/framework/components/upload'
import {save,get,update} from '@/project/service/video'
import {find as findLabel} from '@/project/service/label'
import {findByEnabledIsTrue} from '@/project/service/video-category'

export default {
  name:'uploadDraft',
  props: {
    isUpload:{
      type: Boolean,
      default: () => {
        return false
      }
    },
    idList:{
      type: Array,
      default: () => {
        return []
      }
    }
  },
  components:{ ShopWindow,Upload },
  data() {
    const videoValidator = (rule, value, callback) => {
      if (!this.photoValidate) {
        callback(new Error('请上传短视频'))
      } else {
        callback()
      }
    }
    const photoValidator = (rule, value, callback) => {
      if (!this.photoValidate) {
        callback(new Error('请上传短视频封面'))
      } else {
        callback()
      }
    }
    return {
      //表单校验规则
      ruleValidate: {
        title: [{required: true, message: '不能为空', trigger: 'blur'}],
        content:[{required: true, message: '不能为空', trigger: 'blur'}],
        path: [{ required: true, validator: videoValidator, trigger: 'blur'}],
        cover: [{ required: true, validator: photoValidator, trigger: 'blur'}],
      },
      //编辑对话框中的表单
      uploadForm:{
        videoCategory:{},
        label:[],
      },
      isShopWindow: false,//是否打开窗口橱窗
      channelOptions:[],//频道选择器
      tagOptions:[],//标签选择器
      id:'',
      photoValidate:false,//是否上传了图片
      videoValidate:false,//是否上传了视频
      isFinished:false,
      productList:[],//商品列表
    }
  },
  watch:{
    isUpload(val){
      if(val){
        //获取传过来的id
        this.id = this.idList[0] || ''
        if(this.id){ //编辑
          get({id:this.id},data => {
            console.log(data)
            this.uploadForm = data
            //处理标签列表
            let list = []
            data.labelList.forEach(item => {
              list.push(item.id.toString())
            })
            this.uploadForm.label = list
            if(this.uploadForm.videoCategory){
              this.uploadForm.videoCategory.id = this.uploadForm.videoCategory.id.toString()
            }else{
              this.uploadForm.videoCategory = {}
            }
            this.isFinished = true
            this.videoValidate = true
            this.photoValidate = true
          })
        }else{
          console.log('上传：'+this.id)
          this.isFinished = true
        }
      }
    }
  },
  created(){
    this.getLabelList()
    this.getChannelList()
  },
  methods: {
    //获取标签列表
    getLabelList(){
      let param = {label:{}}
      findLabel(param,data => {
        data.forEach(item => {
          item.id = item.id.toString()
        })
        this.tagOptions = data
        // console.log(this.tagOptions)
      })
    },
    //获取频道列表
    getChannelList(){
      findByEnabledIsTrue({},data => {
        data.forEach(item => {
          item.id = item.id.toString()
        })
        this.channelOptions = data
      })
    },
    //删除短视频触发
    handleVideoRemove(){
      this.videoValidate = false
    },
    //上传短视频成功时触发
    handleVideoSuccess(res){
      console.log('短视频')
      console.log(res)
      this.videoValidate = true
      this.uploadForm.path = res.Location
      this.uploadForm.duration = res.duration
    },
    //删除图片触发
    handleImgRemove(){
      this.photoValidate = false
    },
    //上传图片成功时触发
    handleImgSuccess(res){
      this.photoValidate = true
      this.uploadForm.cover = res.Location
    },
    //提交
    submit(){
      this.$nextTick(() => {
        this.$refs['formValidate'].validate(valid => {
          if(valid){
            // console.log(this.uploadForm)
            //处理请求参数
            let param = {video: this.uploadForm}
            //将表单获取到的标签数组转换成请求规定格式 labelList:[{id:..},{id:..}]
            let list = []
            param.video.label = param.video.label || []
            param.video.label.forEach(item => {
              list.push({id:item})
            })
            param.video.labelList = list
            delete param.video.label
            delete param.video.agent
            delete param.video.reason
            param.productList = this.productList
            if(this.id){ //编辑
              console.log('编辑')
              //处理请求参数
              param.video.id = param.video.id.toString()
              delete param.video.videoCategory.name
              delete param.video.creationTime
              delete param.video.commentsQuantity
              delete param.video.praiseQuantity
              delete param.video.viewerQuantity
              delete param.video.status
              console.log(param)
              update(param,data => {
                // console.log(data)
                if(data == '204'){
                  this.$message.success('编辑成功')
                  this.cancel('',true)
                }
              })
            }else{//上传
              console.log('上传')
              console.log(param)
              save(param,data => {
                console.log(data)
                if(data.id){
                  this.$message.success('上传成功')
                  this.cancel('',true)
                }
              })
            }
          }
        })
      })
    },
    //取消 pointerEvent为elementUI传递参数，不可修改，传入空字符跳过
    cancel(pointerEvent,isUpdate=false){
      // this.$store.commit('clearProductList')
      this.$refs.formValidate.resetFields()
      this.uploadForm.videoCategory = {}
      this.isFinished = false
      //清空添加商品列表
      this.$store.commit('clearProductList')
      this.$emit('close',isUpdate);
    },
    //商品橱窗
    openShopWindow(){
      this.isShopWindow = true
    },
    //关闭商品橱窗
    closeShopWindow(){
      this.isShopWindow = false
      let list = this.$store.state.addProductList.slice(0)
      list.forEach(item => {
        // delete item.position
      })
      // console.log(list)
      this.productList = list
    }
  }
}
</script>

<style lang="less" scoped>
.text {
  color: #a8afae;
}
</style>
